
import AMapLoader from '@amap/amap-jsapi-loader';

const AMapInstance = {}

async function checkAMap () {
    if (!AMapInstance.AMap) {
        window._AMapSecurityConfig = {
            //这里的安全密钥不写会导致 行政区查询等API无法使用
            securityJsCode: "7a6600b62540a0d354363f8d1a405420",
          };
        await AMapLoader.load({
            key: "50efe8ea85c44979db13c0fa5550fc4e", // 申请好的Web端开发者Key，首次调用 load 时必填
            // version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
        .then((amap) => {
            AMapInstance.AMap = amap
        })
        .catch((e) => {
            console.log(e);
        });
    }
}

async function getInstance() {
    await checkAMap()
    return AMapInstance
}


async function getLocation (address) {
    var target;
    await checkAMap()
    var res = await new Promise((resolve, reject) => {
        const geocoder = new AMapInstance.AMap.Geocoder({extensions: "all"});
        geocoder.getLocation(address, function(status, result) {
            resolve({
                status: status,
                result: result
            })
        })
    })

    if (res.status === 'complete' && res.result.info === 'OK') {
        // result中对应详细地理坐标信息
        target = res.result
    }
    
    return target
}

async function getAddress(lng, lat) {
    var target;
    await checkAMap()
    var lnglat = [lng, lat]
    var res = await new Promise((resolve, reject) => {
        const geocoder = new AMapInstance.AMap.Geocoder({extensions: "all"});
        geocoder.getAddress(lnglat, function(status, result) {
            resolve({
                status: status,
                result: result
            })
        })
    })

    if (res.status === 'complete' && res.result.info === 'OK') {
        // result中对应详细地理坐标信息
        target = res.result
    }
    
    return target
}

export { getInstance, getLocation, getAddress}